﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.UI.Mediasend.Logic;
using Medianamik.Core;
using Medianamik.UI.Controls;
using Medianamik.Globalization;
using NLog;
using Telerik.Web.UI;

namespace Medianamik.UI.Mediasend.UserControls
{
    /// <summary>
    /// Affichage des listes de contacts de Mediasend
    /// </summary>
    public partial class ucMailingListSelection : MediasendUserControl
    {
        /// <summary>
        /// Configuration du treeview
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            trvMailingLists.NeedChildren += trvCampaigns_NeedChildren;
            trvMailingLists.NeedSelfAndParents += trvCampaigns_NeedSelfAndParents;

            trvMailingLists.Skin = Skins.DEFAULT_SKIN;
            trvMailingLists.EnableEmbeddedSkins = Skins.DEFAULT_USE_EMBEDDED_SKIN;
        }

        private List<MediasendList> _lists;
        private List<MediasendList> Lists
        {
            get
            {
                if (_lists == null)
                {
                    var mediasend = MediasendManager.Instance.OpenSession(Configuration.Instance.Properties.Username,
                                                                          Configuration.Instance.Properties.Password);
                    _lists = mediasend.GetLists();
                }

                return _lists;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                SetControls();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            string specializedScriptName = "OnClientNodeClickingHandlerFor" + trvMailingLists.ClientID;

            trvMailingLists.OnClientNodeClicking = specializedScriptName;

            //Le script doit exister (différent) pour chaque instance de ComboTree
            string specializedScript = String.Concat("function " + specializedScriptName + "(sender, args) {\n",
                    " var node = args.get_node();\n",
                    "if (node.get_category() == \"Disabled\") {\n",
                        "args.set_cancel(true);}\n",
                        "}\n");
            ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), specializedScriptName, specializedScript, true);
        }

        protected void cvSelectList_Validate(object sender, ServerValidateEventArgs args)
        { 
            int mlstId;
            args.IsValid = int.TryParse(trvMailingLists.SelectedValue, out mlstId);
        }

        #region " TREEVIEW "
        void trvCampaigns_NeedChildren(object sender, Medianamik.UI.Controls.NeedChildrenEventArgs e)
        {
            try
            {
                int parentId;
                if ((e.ParentValue ?? "").Trim() == "")
                {
                    var nodes = from list in Lists
                                where list.Status == ListStatus.Active
                                select
                                    (ITreeItem)
                                    (new TreeItem(String.Format("{0} ({1} {2})", list.Name, list.ContactCount, Translator.Translate("Medianamik_Mediasend","ContactsCount")), 
                                                  list.ID.ToString(), null, null, list.SubList.Count() > 0));

                    e.ChildNodes.AddRange(nodes);
                }
                else if (int.TryParse(e.ParentValue ?? "",out parentId))
                {
                    var parentList = GetList(parentId);

                    if (parentList != null)
                    {
                        var nodes = from list in parentList.SubList
                                    select (ITreeItem)(new TreeItem(String.Format("{0} ({1} {2})", list.Name, list.ContactCount, Translator.Translate("Medianamik_Mediasend", "ContactsCount")), 
                                                                    list.ID.ToString(), null, null, false));

                        e.ChildNodes.AddRange(nodes);
                    }
                }
            }
            catch (Exception exc)
            {
                var logger = LogManager.GetLogger("ActivityLogger");
                if (MediasendManager.Instance.LastError != "")
                    logger.ErrorException("Error while getting Mailing Lists : " + MediasendManager.Instance.LastError, exc);
                else
                    logger.ErrorException("Error while getting Mailing Lists", exc);

                GlobalError = Translator.Translate("Medianamik_Mediasend", "ErrorPleaseContactSupport");
            }
        }

        /// <summary>
        /// Retourne la Liste cherché.
        /// </summary>
        /// <param name="searchedId"></param>
        /// <returns></returns>
        private MediasendList GetList(int searchedId)
        {
            foreach (var list in Lists)
                if (list.ID.Equals(searchedId))
                    return list;

            return default(MediasendList);
        }

        void trvCampaigns_NeedSelfAndParents(object sender, NeedSelfAndParentsEventArgs e)
        {
            e.Items.Add(new TreeItem(Translator.Translate("Medianamik_Mediasend", "MailingList"), null, null, null, true, true, int.MinValue, false));
        }

        #endregion

        #region IMediasendUserControl Members

        public override bool Save()
        {
            int selectedListId;
            if (int.TryParse(trvMailingLists.SelectedValue, out selectedListId))
            {
                //trvMailingLists.SelectedNode.DataItem
                var parent = trvMailingLists.SelectedNode.Parent as RadTreeNode;

                if (parent != null && parent.Value != "")
                {
                    int parentListId;
                    if (int.TryParse(parent.Value, out parentListId))
                    {
                        Data.ListId = parentListId;
                        Data.SubListId = selectedListId;
                    }
                    else
                        return false;
                }
                else
                {
                    Data.ListId = selectedListId;
                    Data.SubListId = null;
                }

                //extraction du sender propre à une liste.
                var loadedList = GetList(Data.ListId.Value);
                if (loadedList != null)
                {
                    if (Data.SenderName.IsNullOrEmpty())
                        Data.SenderName = loadedList.SenderName;

                    if (Data.SenderEmail.IsNullOrEmpty())
                        Data.SenderEmail = loadedList.SenderEmail;
                }

                return true;
            }
            else
                return false;
        }

        public override void SetControls()
        {
            trvMailingLists.CurrentItemValue = Data.SubListId.HasValue ? Data.SubListId.ToString() : Data.ListId.ToString();
        }
        #endregion
    }
}